<template>
  <div>
    <div class="projection_box">
      <TabPoint :pointList="pointList"></TabPoint>

      <div class="content" id="pointBox">
        <!-- 查询 -->
        <Search :form="searchForm" v-model="searchForm"></Search>
        <!-- 注解 -->
        <Notes :items="treeItems" ref="notesRef"></Notes>
        <div id="handlePoin">
          <!-- 流处理 -->
          <div class="form_title">输入</div>
          <div class="my_required title">条件</div>
          <FlowHnadle
            :sourceCellNames="sourceCellNames"
            ref="flowHnadleRef"
            title="条件"
          ></FlowHnadle>
          <div class="source_box">
            <div class="my_required title">逻辑语句</div>
            <PopoverInput
              objKey="Operator"
              v-model="logic"
              keys="conductValue"
            ></PopoverInput>
          </div>
        </div>
        <!-- 投影 -->
        <Projection
          :objKey="'funArrAllNoAttr'"
          objKeyFilter="funArrAllNoAttrCondition"
          :attributeList="attributeList"
          v-model="grouping"
          :extensionsLR="extensionsLR"
        ></Projection>
        <!-- 输出 -->
        <Output
          @handDelOrderBy="handDelOrderBy"
          @handAddOrderBy="handAddOrderBy"
          :attributeList="attributeList"
          v-model="output"
        ></Output>
      </div>
    </div>
    <!-- 确认取消公共组件 -->
    <top-operation-button @submit="submit" @handClose="handClose" />
  </div>
</template>

<script>
import TopOperationButton from "../CommonComponents/TopOperationButton";
import TabPoint from "@/components/TabPoint";
import Search from "./component/Search.vue";
import FlowHnadle from "./component/FlowHandle.vue";
import Notes from "./component/Notes.vue";
import Projection from "@/components/Projection";
import Output from "@/components/Output";
import { getMetadata } from "@/api/project";
import { validate } from "./js/validate";
import PopoverInput from "@/components/PopoverInput";
import {
  setFunctiondata,
  setStreamHandlerList,
  settargetCellAttr,
  setSourceCellAttr,
  setUserAttr,
  setTypeName,
} from "../projectionPage/js/index";
import { mapGetters } from "vuex";
import { generateId, reverseJson, empty } from "@/utils/index";
import _ from "lodash";
import inputSource from "@/store/modules/inputSource";
import {
  mapParameterValues,
  obtainStreamFunctionsFromResponse,
} from "../windowsPage/js/index";
export default {
  components: {
    TopOperationButton,
    Output,
    TabPoint,
    Search,
    FlowHnadle,
    Notes,
    Projection,
    PopoverInput,
  },
  props: {
    nodeDataRight: {
      type: Object,
      default: () => {},
    },
    type: {
      type: String,
      default: "",
    },
  },

  computed: {
    ...mapGetters(["extensions", "metadata"]),
    // 后一个节点的属性
    relateData() {
      // relateData.targetCell.name
      return this.$store.state.projection.relateData;
    },
    extensionsLR() {
      if (JSON.stringify(this.$store.state.projection.extensions) !== "{}") {
        let attrArr =
          this.$store.state.projection.extensions.funArrAllNoAttr.find(
            (item) => item.name == "属性"
          )?.list || [];
        return attrArr;
      } else {
        return [];
      }
    },
  },
  data() {
    return {
      logic: "",
      // 查询
      searchForm: {
        queryName: "",
        from: "",
      },
      // 输出
      output: {
        orderCh: false,
        orderBy: [], //按属性排序
        checkedLimit: false, //限制
        limit: "",
        checkedOffset: false, //位移
        offset: "",
        checkedOutputRateLimit: false, //输出速率
        outputRateLimit: "",
        // 操作下边的数据
        queryOutput: {
          type: "INSERT",
          target: "", //插入
          output: {
            eventType: "CURRENT_EVENTS", //事件类型
            // set选中传-选中整个都不传
            checkedSet: false,
            set: [],
          },
          // on: "",
        },
      },
      // 投影
      grouping: {
        groupBy: [], //按属性分组
        having: "", //过滤
        attrChecked: false,
        checkedFilter: false,
        select: {
          type: "ALL", //ALL USER_DEFINED 所有属性,用户自定义属性
          value: [], //用户自定义属性
        },
      },
      treeItems: [],
      form: { name: "" },
      rules: {},
      firstAttr: {},
      pointList: [
        {
          name: "查询",
          id: "searchPoin",
          val: "searchPoin",
        },
        {
          name: "注释",
          id: "notesPoin",
          val: "notesPoin",
        },
        {
          name: "输入",
          id: "handlePoin",
          val: "handlePoin",
        },
        {
          name: "投影",
          id: "prijectionPoin",
          val: "prijectionPoin",
        },
        {
          name: "输出",
          id: "output",
          val: "output",
        },
      ],
      attributeList: [],
      streamHandlerList: [],
      targetCellAttr: [],
      sourceCellNames: [],
    };
  },

  watch: {
    nodeDataRight: {
      handler: async function (newData, oldData) {
        let tempdata = _.cloneDeep(newData);
        console.log(tempdata, "tempdata");
        const { objectState } = tempdata;
        const {
          limit,
          offset,
          outputRateLimit,
          queryOutput,
          orderBy,
          groupBy,
          having,
          select,
          queryName,
          queryInput,
          annotationListObjects,
        } = tempdata;
        const { sourceCell } = tempdata.relateData;
        console.log(tempdata, "节点信息");
        this.searchForm.queryName = tempdata.queryName || "";
        const name = tempdata.relateData.targetCell.name;
        this.searchForm.from = name || "";
        // 后一个节点属性整理
        tempdata.relateData.targetCell.attributeList = settargetCellAttr(
          tempdata.relateData.targetCell.attributeList,
          name
        );

        if (
          tempdata.relateData.sourceCell &&
          tempdata.relateData.sourceCell.length !== 0
        ) {
          if (_.isArray(sourceCell)) {
            this.sourceCellNames = sourceCell;
            let souAttrArr = [];
            sourceCell.forEach((item) => {
              souAttrArr = souAttrArr.concat(
                souAttrArr,
                setSourceCellAttr(item.attributeList, item.name)
              );
            });
          } else {
            this.sourceCellNames = [sourceCell];
            // let newAttrList = _.cloneDeep(sourceCell.attributeList);
            // sourceCell.attributeList = newAttrList.map((item) => {
            //   return {
            //     ...item,
            //     name: sourceCell.name + "." + item.name,
            //   };
            // });
          }
        }

        this.$store.commit("projection/setRelateData", tempdata.relateData);
        this.targetCellAttr = tempdata.relateData.targetCell.attributeList;
        // 设置来源节点名称
        // this.$store.commit(
        //   "projection/setQueryInput",
        //   tempdata.relateData.sourceCell.name
        // );
        if (tempdata.relateData.targetCell) {
          this.attributeList = _.cloneDeep(
            tempdata.relateData.targetCell.attributeList
          );
          // this.grouping = [
          //   { id: generateId(), name: "", attributeList: this.attributeList },
          // ];
          this.attributeList.forEach((item) => {
            item.id = generateId();
            item.value = item.name;
            item.disabled = false;
          });
        }
        // if (queryInput && queryInput.from) {
        //   this.searchForm.from = queryInput && queryInput.from;
        // } else {
        //   this.searchForm.from = tempdata.relateData.sourceCell.name;
        // }
        if (queryInput && queryInput.logic) {
          this.logic = queryInput.logic;
        } else {
          this.logic = "";
        }

        this.$nextTick(async () => {
          // 获取整理的抽屉数据-同步处理
          // await this.$store.dispatch(
          //   "projection/getMetadata",
          //   this.nodeDataRight.relateData
          // );
          // 传递节点数据-合并metadata的数据
          this.$store.commit("projection/setExtensions", {
            relateData: tempdata.relateData,
            // isName: true,
          });
          // 封装流处理数据
          if (queryInput) {
            let { conditionList } = queryInput;
            if (conditionList.length !== 0) {
              // conditionList
              conditionList.forEach((item) => {
                // 添加一个随机id-做增删改
                item.id = generateId();
                let attr = this.sourceCellNames.find(
                  (f) => f.name == item.streamName
                );
                item.attributeList = attr.attributeList;
                if (item.streamHandlerList.length !== 0) {
                  item.streamHandlerChecked = true;
                  item.streamHandlerList = this.getFunNamePar(
                    item.streamHandlerList
                  );
                  // item.streamHandlerList = setStreamHandlerList(
                  //   item.streamHandlerList || [],
                  //   this.extensions
                  // );
                }
              });
              // 把conditionList添加到逻辑语句下拉框内

              this.$refs.flowHnadleRef.editableTabs = conditionList;
              this.$refs.flowHnadleRef.editableTabsValue = conditionList[0].id;
            } else {
              conditionList = [
                {
                  conditionId: "e1",
                  streamName: "",
                  streamHandlerList: [],
                  streamHandlerChecked: false,
                  id: "1",
                },
              ];
            }
            this.$store.commit("projection/setUserInput", conditionList);
            this.$store.commit("projection/setOperator", conditionList);
          } else {
            const conditionList = [
              {
                conditionId: "e1",
                streamName: "",
                streamHandlerList: [],
                streamHandlerChecked: false,
                id: "1",
              },
            ];
            this.$store.commit("projection/setUserInput", conditionList);
            this.$store.commit("projection/setOperator", conditionList);
          }
        });

        if (annotationListObjects && annotationListObjects.length !== 0) {
          this.$nextTick(() => {
            // 自定义注解整理
            this.$refs.notesRef.treeItems = reverseJson(
              annotationListObjects,
              "dist"
            );
          });
          // treeData
          // const { name, elements } = annotationListObjects[0];
          const index = annotationListObjects.findIndex(
            (i) => i.name == "dist"
          );
          // dist数据整理回显
          if (index != -1) {
            this.$nextTick(() => {
              this.$refs.notesRef.form = {
                parallel: annotationListObjects[index].elements.find(
                  (item) => item.key == "parallel"
                ).value,
                execGroup: annotationListObjects[index].elements.find(
                  (item) => item.key == "execGroup"
                ).value,
                checkedImplement: annotationListObjects[index].elements.find(
                  (item) => item.key == "execGroup"
                ).value
                  ? true
                  : false,
                checkedParallel: annotationListObjects[index].elements.find(
                  (item) => item.key == "parallel"
                ).value
                  ? true
                  : false,
              };
              this.$refs.notesRef.checked = true; //打开async输入框
            });
          } else {
            this.$nextTick(() => {
              this.$refs.notesRef.form = {
                parallel: "",
                execGroup: "",
                checkedParallel: false,
                checkedImplement: false,
              };
              this.$refs.notesRef.checked = false; //打开async输入框
            });
          }
        }
        this.searchForm.queryName = queryName;
        // 输出数据回显
        if (limit) {
          this.output.checkedLimit = true;
        } else {
          this.output.checkedLimit = false;
        }
        if (offset) {
          this.output.checkedOffset = true;
        } else {
          this.output.checkedOffset = false;
        }
        if (orderBy && orderBy.length != 0) {
          this.output.orderCh = true;
          this.output.orderBy = orderBy;
        } else {
          // 如果orderBy没值,给一个默认值,选中的时候方便展示
          this.output.orderCh = false;
          this.output.orderBy = [
            {
              id: generateId(),
              attrValue: "",
              sortValue: "",
              attributeList: this.attributeList,
            },
          ];
        }
        if (outputRateLimit) {
          this.output.checkedOutputRateLimit = true;
        } else {
          this.output.checkedOutputRateLimit = false;
        }
        this.output = {
          ...this.output,
          limit,
          offset,
          outputRateLimit,
        };
        // set有值
        this.output.queryOutput.target = tempdata.relateData.targetCell.name;
        if (queryOutput && queryOutput.output.eventType) {
          this.output.queryOutput.output.eventType =
            queryOutput.output.eventType;
        }
        if (
          queryOutput &&
          queryOutput.output.set &&
          queryOutput.output.set.length !== 0
        ) {
          this.output.queryOutput.output.checkedSet = true;
        } else {
          this.output.queryOutput.output.checkedSet = false;
        }

        // 判断过滤是否有值-有值打开
        if (having && having != "") {
          this.grouping.checkedFilter = true;
          this.grouping.having = having;
        } else {
          this.grouping.checkedFilter = false;
        }
        // 判断是否是用户自定义
        if (select && select.value && select.value.length !== 0) {
          this.grouping.select.type = select.type;
          // this.grouping.attrChecked = true;
          // 后一个节点的属性名是唯一的 此处要进行合并和后一个节点关联 this.targetCellAttr
          this.grouping.select.value = setUserAttr(
            select.value,
            this.targetCellAttr
          );
        } else {
          // this.grouping.attrChecked = false;
          this.grouping.select.value = setUserAttr([], this.targetCellAttr);
        }
        if (groupBy && groupBy.length != 0) {
          this.grouping.attrChecked = true;
          this.grouping.groupBy = groupBy;
        } else {
          this.grouping.attrChecked = false;
          this.grouping.groupBy = [];
        }
        if (objectState != "new") {
        }
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    // this.getMetadata();
    // this.grouping.select.value = this.relateData.targetCell.attributeList;
    // // 来源
    // this.searchForm.from = this.relateData.sourceCell.name;
    // // 插入
    // this.output.queryOutput.target = this.relateData.targetCell.name;
    // // 输出-按属性排序
    // this.output.orderBy =
    //   this.relateData.targetCell.attributeList.length !== 0
    //     ? [this.relateData.targetCell.attributeList[0]]
    //     : [];
  },
  methods: {
    getFunNamePar(streamHandlerList) {
      const newstreamHandlerList = _.cloneDeep(streamHandlerList);
      newstreamHandlerList.forEach((item) => {
        item.title = setTypeName(item.type);
        if (item.type !== "FILTER") {
          const key =
            item.type == "WINDOW" ? "windowFunctionNames" : "streamFunctions";
          item.value.parameters = mapParameterValues(
            {
              function: item.value.function,
              parameters: item.value.parameters,
            },
            obtainStreamFunctionsFromResponse(this.metadata)[key]
          );
        }
      });
      return newstreamHandlerList;
    },
    //删除orderBy
    handDelOrderBy(i) {
      this.output.orderBy.splice(i, 1);
    },
    // 添加
    handAddOrderBy() {
      this.output.orderBy.push({
        id: generateId(),
        attrValue: "",
        sortValue: "ASC",
        order: "ASC",
        attributeList: this.attributeList,
      });
    },
    handClose() {
      this.$emit("handClose");
    },
    isCheck() {
      // 在提交 的时候 判断是否选中清空数据
      // 是否有用户自定义属性
      if (this.grouping.select.type == "ALL") {
        this.grouping.select.value = "*";
      }
      // 按属性分组
      if (!this.grouping.attrChecked) {
        this.grouping.groupBy = [];
      }
      // 按过滤分组
      if (!this.grouping.checkedFilter) {
        this.grouping.having = "";
      }
      // 按属性排序
      if (!this.output.orderCh) {
        this.output.orderBy = [];
      }
      // 限制
      if (!this.output.checkedLimit) {
        this.output.limit = 0;
      }
      // 位移
      if (!this.output.checkedOffset) {
        this.output.offset = 0;
      }
      // 输出速率
      if (!this.output.checkedOutputRateLimit) {
        this.output.outputRateLimit = "";
      }
      // set如果没选中 不传set
      if (!this.output.queryOutput.output.checkedSet) {
        this.output.queryOutput.output.set = undefined;
      }
    },
    submit() {
      // 流处理 queryInput
      // 注解
      const notesList = this.$refs.notesRef.getNotes();
      const treeItems = this.$refs.notesRef.treeItems;
      const { conditionList } = this.$refs.flowHnadleRef.getFlowData();
      const queryInput = {
        type: this.type, //PROJECTION
        logic: this.logic,
        conditionList,
        // from: this.searchForm.from,
        // streamHandlerList,
        // streamHandlerChecked,
      };
      // 判断选择框是否选择-没有选择的清空数据
      this.isCheck();
      // 最终的提交数据
      const succData = {
        // 输出
        ...this.output,
        // 投影
        ...this.grouping,
        // 注解
        ...notesList,
        queryName: this.searchForm.queryName,
        queryInput,
        name: this.searchForm.queryName,
        treeItems: treeItems,
        relateData: this.nodeDataRight.relateData,
      };
      console.log(succData, "最终的数据");
      // 表单验证
      try {
        if (validate(succData)) {
          let returnData = {
            display: false,
            type: "queryLists",
            keyType: this.type,
            objectState: this.nodeDataRight.objectState,
            nodeData: succData,
            nodeDataRight: this.nodeDataRight,
          };
          // 存储到vuex-后续不需要可以删除
          this.$emit("returnSource", returnData);
        }
      } catch (error) {
        console.log(error.message, "完善条件");
        this.$refs.flowHnadleRef.editableTabsValue = error.message;
      }
    },
    // valiFow(){

    // }
    // async getMetadata() {
    //   const { data } = await getMetadata();
    //   // 数据整理(函数,过滤,窗口)
    //   let extensionsObj = setFunctiondata(data, this.nodeDataRight.relateData);
    //   //存入vuex
    //   this.$store.commit("projection/setMetadata", extensionsObj);
    // },
  },
};
</script>

<style lang='scss' scoped>
.source_box {
  margin-bottom: 16px;
  margin-top: 16px;
  .title {
    margin-bottom: 12px;
  }
}
.projection_box {
  display: flex;
  width: 100%;
  #handlePoin /deep/ .el-tabs__header.is-top {
    margin-bottom: 0;
  }
  #handlePoin /deep/ .el-tabs__nav-wrap::after {
    background-color: transparent;
  }
  #handlePoin /deep/ .el-tabs__new-tab {
    width: 60px;
    min-width: 60px;
    height: 100%;
    border: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    order: 1;
    white-space: nowrap;
    .el-icon-plus {
      color: #707070;
      font-size: 14px;
    }
    &::after {
      content: "添加条件";
      color: #707070;
      font-size: 12px;
    }
  }
  /* /deep/ .el-tabs__new-tab */
  .content {
    padding-right: 10px;
    width: 100%;
    height: 80vh;
    overflow: scroll;
    overflow-x: hidden;
  }
}
</style>